package com.google.code.stalkernet.node;

/**
 * Contains various useful classes for work with nodes.
 *
 * @author Mikhail Vladimirov
 */
public class NodeUtils
{
    private NodeUtils ()
    {
        throw new Error ("Do not instantiate me");
    }

    /**
     * Create {@link NodeID} object from given sequence of bytes.
     *
     * @param bytes an array of bytes
     * @return {@link NodeID} object
     */
    public static NodeID createNodeID (byte [] bytes)
    {
        if (bytes == null)
            throw new IllegalArgumentException ("Bytes is null");

        return new MyNodeID (bytes);
    }

    /**
     * Format {@link NodeID} object as human-readable string.
     *
     * @param nodeID {@link NodeID} object to format
     * @return human-readable representation of given {@link NodeID} object
     */
    public static String formatNodeID (NodeID nodeID)
    {
        if (nodeID == null)
            throw new IllegalArgumentException ("Node ID is null");

        return formatBytes (nodeID.getBytes ());
    }

    private static class MyNodeID extends AbstractNodeID
    {
        private final byte [] bytes;

        public MyNodeID (byte [] bytes)
        {
            if (bytes == null)
                throw new IllegalArgumentException ("Bytes is null");

            this.bytes = bytes.clone ();
        }

        @Override
        public byte [] getBytes ()
        {
            return bytes.clone ();
        }
    }

    private static String formatBytes (byte [] bytes)
    {
        int count = bytes.length;
        StringBuilder result = new StringBuilder (count * 2);
        for (int i = 0; i < count; i++)
            for (int j = 4; j >= 0; j -= 4)
                result.append (
                    "0123456789ABCDEF".charAt ((bytes [i] >>> j) & 0x0F));

        return result.toString ();
    }
}
